package com.xn.app.muying.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.xn.app.muying.R;
import com.xn.app.muying.fragment.EducationFragment;
import com.xn.app.muying.fragment.HomeFragment;
import com.xn.app.muying.fragment.MineFragment;
import com.xn.app.muying.fragment.MonitoringFragment;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AndroidBug54971Workaround;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.MyApplication;
import com.xn.app.muying.view.MyRadioButton;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONObject;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends BaseActivity {
    private RadioGroup tab_rg;
    public static Activity mActivity;
    private long mExitTime;
    private Fragment mContent;
    private HomeFragment homeFragment;
    private EducationFragment educationFragment;
    private MineFragment mineFragment;
    private MonitoringFragment monitoringFragment;
    private FragmentManager ragmentManager;
    private FragmentTransaction transaction;
    //底部栏数量
    private static final int tabNumber = 5;
    private DBManager db = null;
    //接受用户信息
    private String name = null;
    //商城按钮
    private LinearLayout navigation_bar_item_shop=null;
    //引导蒙版
    private ImageButton yd_imgbutton=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidBug54971Workaround.assistActivity(findViewById(android.R.id.content));
        //如果手机系统大于等于5.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //如果手机系统大于等于4.4并且小于等于5.0
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main);
        //统一管理activity
        MyApplication.getInstance().addActivity(this);
        mActivity = MainActivity.this;
        db = new DBManager(this);
        tab_rg = (RadioGroup) findViewById(R.id.main_rg);
        yd_imgbutton= (ImageButton) findViewById(R.id.yd_imgbutton);
        yd_imgbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Constants.setStringByName(MainActivity.this,"yd_activity","1");
                yd_imgbutton.setVisibility(View.GONE);
            }
        });
        navigation_bar_item_shop= (LinearLayout) findViewById(R.id.navigation_bar_item_shop);
        navigation_bar_item_shop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent();
                intent.putExtra("title", "营养中心");
                intent.putExtra("url", APIMethod.WeiDian);
                intent.setClass(MainActivity.mActivity, WebActivity.class);
                startActivity(intent);
            }
        });
        tab_rg.setOnCheckedChangeListener(checkedChangeListener);
        //注册通知广播
        registerBoradcastReceiver();
        //开启诸葛IO统计
        //初始化分析跟踪
        ZhugeSDK.getInstance().init(getApplicationContext());
        //功能实现
        initFragment();
        //查询是否进入过新手引导
        String  ydStr=Constants.getStringByName(this,"yd_activity");
        if(ydStr.length()<=0){
            yd_imgbutton.setVisibility(View.VISIBLE);
            yd_imgbutton.setBackgroundResource(R.mipmap.ydmb);
        }
    }

    public void initFragment() {
        //定义用户属性
        try {
            //获取唯一标示
            name = db.select("tel");
            JSONObject personObject = new JSONObject();
            //如果唯一标示不为空
            if (name != null && !name.equals("") && !name.equals("null")) {
                personObject.put("mobile", name);
                //如果用户姓名不为空
                if (db.select("name") != null) {
                    personObject.put("name", db.select("name"));
                } else {
                    //如果用户姓名为空
                    personObject.put("name", "");
                }
            } else {
                //如果唯一标示位空，填入空值
                name = "";
                personObject.put("mobile", "");
                personObject.put("name", "");
            }
            //标识用户
            ZhugeSDK.getInstance().identify(getApplicationContext(), name,
                    personObject);
            //事件记录
            ZhugeSDK.getInstance().track(getApplicationContext(), "在线人次");
            //初始化组件
            mineFragment = new MineFragment();
            homeFragment = new HomeFragment();
            monitoringFragment = new MonitoringFragment();
            educationFragment = new EducationFragment();
            ragmentManager = getSupportFragmentManager();
            transaction = ragmentManager.beginTransaction();
            transaction.add(R.id.main_frame, homeFragment).commit();
            mContent = homeFragment;
            //更新数据广播
            IntentFilter filter = new IntentFilter("bei_er");
            registerReceiver(broadcastReceiver, filter);

            //网络监听广播
//        IntentFilter intentFilter=new IntentFilter();
//        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
//        networkConnectChangedReceiver=new NetworkConnectChangedReceiver();
//        registerReceiver(networkConnectChangedReceiver,intentFilter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void switchContent(Fragment to) {
        //如果需要展示的fragment不是当前fragment
        if (mContent != to) {
            transaction = ragmentManager.beginTransaction();
            //如果需要打开的fragment没有存在，先创建在显示
            if (!to.isAdded()) {
                transaction.hide(mContent);
                transaction.add(R.id.main_frame, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
                mContent = to;
            } else {
                //如果需要打开的fragment存在，就显示
                transaction.hide(mContent);
                transaction.show(to).commit(); // 隐藏当前的fragment，显示下一个
                mContent = to;
            }
        }
    }

    RadioGroup.OnCheckedChangeListener checkedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            if(checkedId!=R.id.navigation_bar_item_shop){
                for (int i = 0; i < tabNumber; i++) {
                    if(i!=2){
                        MyRadioButton tabrb = (MyRadioButton) tab_rg.getChildAt(i);
                        if (tabrb.isChecked()) {
                            tabrb.setTextColor(getResources().getColor(R.color.sys_fen));
                        } else {
                            tabrb.setTextColor(getResources().getColor(R.color.main_tab_text));
                        }
                    }
                }
                switch (checkedId) {
                    case R.id.navigation_bar_item_home:
                        switchContent(homeFragment);
                        break;
                    case R.id.navigation_bar_item_monitoring:
                        switchContent(monitoringFragment);
                        break;
                    case R.id.navigation_bar_item_mine:
                        switchContent(mineFragment);
                        break;
                    case R.id.navigation_bar_item_education:
                        switchContent(educationFragment);
                        break;
                }
            }

        }
    };

    /**
     * 信息修改后返回
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            int verification = intent.getIntExtra("bei_er", -1);
            //0  获取数据    1 取消数据
            if (!TextUtils.isEmpty(action)) {
                //更新主页信息
                homeFragment.HomeFragment(verification);
                //更新个人信息
                mineFragment.MineFragment(verification);
//                //更新百科页面
//                educationFragment.EducationFragment(verification);
            }
        }
    };

    @Override
    protected void onDestroy() {
        unregisterReceiver(broadcastReceiver);
//        unregisterReceiver(networkConnectChangedReceiver);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                } else {
                    //本次数据统计结束
                    ZhugeSDK.getInstance().flush(getApplicationContext());
                    //统一管理activity
                    MyApplication.getInstance().exit();
                }
                return true;
            }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //初始化分析跟踪
        homeFragment.HomeFragment(2);
        JPushInterface.onResume(this);//极光推送统计
        JPushInterface.resumePush(this);//启动极光推送
    }

    @Override
    protected void onStop() {
        super.onStop();
        homeFragment.HomeFragment(3);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onResume(this);
    }
}
